package com.kordar.admin.kernel.thlibs;

import com.kordar.admin.kernel.util.RequestHolder;
import com.kordar.admin.modular.sys.enums.AdminType;
import com.kordar.auth.Admin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.standard.processor.AbstractStandardConditionalVisibilityTagProcessor;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.Optional;

public class LayuiAuthProcessor extends AbstractStandardConditionalVisibilityTagProcessor {

    private static final String ATTRIBUTE_NAME = "auth";
    private static final int PRECEDENCE = 300;

    protected LayuiAuthProcessor(String dialectPrefix) {
        super(TemplateMode.HTML, dialectPrefix, ATTRIBUTE_NAME, PRECEDENCE);
    }

    @Override
    protected boolean isVisible(ITemplateContext iTemplateContext, IProcessableElementTag iProcessableElementTag, AttributeName attributeName, String s) {
        //自定义属性值。
        String attributeValue = Optional.ofNullable(iProcessableElementTag.getAttributeValue(attributeName)).orElse("").trim();
        if (attributeValue.isEmpty()) {
            return false;
        }

        Admin admin = (Admin) RequestHolder.getRequest().getAttribute("admin");
        if (admin.getType().equals(AdminType.TYPE_SUPER.getCode())) {
            return true;
        }

        System.out.println(attributeValue);

        Subject subject = SecurityUtils.getSubject();
        return subject.isPermitted(attributeValue);
    }
}

